/**
 * FileHelper
 *
 * Released under Apache License, Version 2.0.
 */

package bsp.helper;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.Vector;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileHelper
{
	protected FileHelper()
	{
	}
	
	/**
	 * Get extension of file.
	 * 
	 * @param input File name
	 * @param extSeparator Extension separator
	 * @return String - File extension
	 */
	public static String getExtension(String input, String extSeparator)
	{
		int dot = input.lastIndexOf(extSeparator);
		return input.substring(dot + 1);
	}

	/**
	 * Get name of file without extension.
	 * 
	 * @param input
	 * @param pathSeparator
	 * @param extSeparator
	 * @return
	 */
	public static String getFilenameWithoutExtension(String input, String pathSeparator, String extSeparator)
	{ 
		int dot = input.lastIndexOf(extSeparator);
		int sep = input.lastIndexOf(pathSeparator);
		return input.substring(sep + 1, dot);
	}

	/**
	 * Get file path.
	 * 
	 * @param input
	 * @param pathSeparator
	 * @return
	 */
	public static String getPath(String input, String pathSeparator)
	{
		int sep = input.lastIndexOf(pathSeparator);
		return input.substring(0, sep);
	}
	
	/**
	 * Load file into a string separated by "\n".
	 */
	public static String loadFileIntoString(String filename)
	{
		String retVal = null;
		String str;
		StringBuffer data;
		BufferedReader br = null;
		boolean bFirst = true;
		
		try {
			data = new StringBuffer(5000);
			br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(filename))));
			
			while ( (str = br.readLine()) != null ) {
				if ( bFirst == false ) {
					data.append("\n").append(str);
				} else {
					bFirst = false;
					data.append(str);
				}
			}
			
			br.close();
			retVal = data.toString();
		} catch ( IOException e ) {
			e.printStackTrace();
			retVal = null;
		}
		
		return retVal;
	}
	
	/**
	 * Load file into a string separated by "\n".
	 */
	public static String loadFileIntoString(InputStream is)
	{
		String retVal = null;
		String str;
		StringBuffer data;
		BufferedReader br = null;
		boolean bFirst = true;
		
		try {
			data = new StringBuffer(5000);
			br = new BufferedReader(new InputStreamReader(new DataInputStream(is)));
			
			while ( (str = br.readLine()) != null ) {
				if ( bFirst == false ) {
					data.append("\n").append(str);
				} else {
					bFirst = false;
					data.append(str);
				}
			}
			
			br.close();
			retVal = data.toString();
		} catch ( IOException e ) {
			e.printStackTrace();
			retVal = null;
		}
		
		return retVal;
	}
	
	/**
	 * Load file contents into a Vector of Strings.
	 * 
	 * @param filename
	 * @return
	 */
	public static Vector<String> loadFileIntoStringVector(String filename)
	{
		Vector<String> retVal = null;
		String str;
		BufferedReader br = null;
		
		try {
			retVal = new Vector<String>();
			
			br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(filename))));
			
			while ( (str = br.readLine()) != null ) {
				retVal.add(str);
			}
			
			br.close();
		} catch ( IOException e ) {
			e.printStackTrace();
			retVal = null;
		}
		
		return retVal;
	}
	
	/**
	 * Copy file from source to destination using file handle.
	 * 
	 * @param inFile
	 * @param outFile
	 * @return
	 */
	public static boolean copyFile(InputStream inStream, File outFile)
	{
		boolean retVal = false;
		FileWriter out = null;
		int c;
		
		try {
			out = new FileWriter(outFile);

			while ( (c = inStream.read()) != -1 ) {
				out.write(c);
			}

			out.close();
			
			retVal = true;
		} catch ( IOException ex ) {
			ex.printStackTrace();
		}
		
		return retVal;
	}
	
	/**
	 * Copy file from source to destination using file handle.
	 * 
	 * @param inFile
	 * @param outFile
	 * @return
	 */
	public static boolean copyFile(File inFile, File outFile)
	{
		boolean retVal = false;
		FileReader in = null;
		FileWriter out = null;
		int c;
		
		try {
			in = new FileReader(inFile);
			out = new FileWriter(outFile);

			while ( (c = in.read()) != -1 ) {
				out.write(c);
			}

			in.close();
			out.close();
			
			retVal = true;
		} catch ( IOException ex ) {
			ex.printStackTrace();
		}
		
		return retVal;
	}
	
	/**
	 * Copy file from source to destination using path names.
	 * @param srcPath
	 * @param destPath
	 * @return
	 */
	public static boolean copyFile(String srcPath, String destPath)
	{
		boolean retVal = false;
		File inFile = null, outFile = null;
		
		inFile = new File(srcPath);
		outFile = new File(destPath);
			
		retVal = copyFile(inFile, outFile);
		
		return retVal;
	}
	
	/**
     * Overwrite file contents.
     */
    public static boolean overwriteFile(File f, boolean bSecure)
    {
    	boolean retVal = false;
    	
    	try {
			RandomAccessFile pw = new RandomAccessFile(f, "rw");
			long len = f.length();
			for ( long x = 0; x < len; x++ ) {
				pw.write('0');
			}
			pw.close();
			retVal = true;
    	} catch ( FileNotFoundException e ) {
			e.printStackTrace();
    	} catch ( IOException e ) {
			e.printStackTrace();
    	}
    	
    	return retVal;
    }
    
    /**
     * Recursively delete files.
     */
	public static void recursiveDelete(File f)
	{
		File[] files = f.listFiles();
		if ( files == null ) {
			return;
		}
		for (int i = 0; i < files.length; i++) {
			if ( files[i].isDirectory() ) {
				recursiveDelete(files[i]);
			}
			
			files[i].delete();
		}
	}
	
	/**
     * Recursively delete files securely.
     */
    public static void recursiveDelete(File f, boolean bSecure)
	{
		File[] files = f.listFiles();
		
		if ( files == null ) {
			return;
		}

		for ( int i = 0; i < files.length; i++ ) {
			if ( files[i].isDirectory() ) {
				recursiveDelete(files[i], bSecure);
			} else if ( files[i].isFile() && bSecure == true ) {
				overwriteFile(files[i], bSecure);
			}
			
			files[i].delete();
		}
	}
    
    public static File getDirectoryHandle(File parentPath, String dirName)
    {
    	File childDir = new File(parentPath, dirName);
		return childDir;
    }
    
    public static File getDirectoryHandle(File parentPath, String dirList, String separator)
    {
    	File child = null, parent = null;
    	String[] tok = StringHelper.tokenize2StringArray(dirList, separator);
    	
    	parent = parentPath;
    	for ( int i = 0; i < tok.length; i++ ) {
    		child = new File(parent, tok[i]);
    		parent = child;
    		child = null;
		}
		
		return child;
    }
    
    public static File getDirectoryHandleCreateIfRequired(File parentPath, String dirName)
    {
    	File childDir = new File(parentPath, dirName);
		if ( childDir.exists() == false ) {
			childDir.mkdir();
		}
		
		return childDir;
    }
    
    public static File getDirectoryHandleCreateIfRequired(File parentPath, String dirList, String separator)
    {
    	File child = null, parent = null;
    	String[] tok = StringHelper.tokenize2StringArray(dirList, separator);
    	
    	parent = parentPath;
    	for ( int i = 0; i < tok.length; i++ ) {
    		child = new File(parent, tok[i]);
    		if ( child.exists() == false ) {
    			child.mkdir();
    		}
    		parent = child;
    		child = null;
		}
		
		return child;
    }
}

/* end */
